package com.fingard.dsp.bank.directbank.zyb02;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.fingard.FGBiz;
import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.IpHelper;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class ZYB02Base extends DirectBase implements ITcpClient {
    public static final String OK = "OK";
    public static final String TMPSTATUS = "S";
    public static final String RET_CODE = "000000";
    public static final String DEBIT = "D";
    public static final String CREDIT = "C";
    public static final String FILESEPARATOR = "|";
    public static final DateFormat2 TIME12FORMAT = new DateFormat2("HH:mm:ss.SSS");
    public static final BigDecimal maxAmout = new BigDecimal(1000000.00);

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected void writeCommon(XmlTextWriter xmlWriter, ZYB02Header bankHeader) throws Exception {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("_TransactionId", bankHeader.TRAN_CODE);
        xmlWriter.writeElementString("_MCHTimestamp", bankHeader.TRAN_DATE + " " + bankHeader.TRAN_TIMESTAMP);
        xmlWriter.writeElementString("_MChannelId", getBankConfig().getMapValueByKey("Sys_Head", "CONSUMER_ID"));
        //_DeptSeq在配置文件中原先配的值为25 20181213
        //xmlWriter.writeElementString("_DeptSeq", getBankConfig().getMapValueByKey("ACROSSBANK","_DeptSeq"));
        xmlWriter.writeElementString("_DeptId", getBankConfig().getMapValueByKey("ACROSSBANK","_DeptId"));
        xmlWriter.writeElementString("_MCHJnlNo", bankHeader.SEQ_NO);
        /*xmlWriter.writeElementString("_AccessIp", getBankConfig().getMapValueByKey("ACROSSBANK","_AccessIp"));
        xmlWriter.writeElementString("_AccessHost", getBankConfig().getMapValueByKey("ACROSSBANK","_AccessHost"));
        xmlWriter.writeElementString("_ChannelIP", getBankConfig().getMapValueByKey("ACROSSBANK","_ChannelIP"));*/
        xmlWriter.writeElementString("_AccessIp", bankHeader.USER_IP);
        xmlWriter.writeElementString("_AccessHost", bankHeader.USER_IP);
        xmlWriter.writeElementString("_ChannelIP", bankHeader.SERVER_IP);
        xmlWriter.writeElementString("_locale", getBankConfig().getMapValueByKey("ACROSSBANK","_locale"));
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("Body");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, ZYB02Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.TRAN_CODE)) {
            throw new Exception("未赋值trsCode");
        }

        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Sys_Head");

        xmlWriter.writeElementString("TRAN_CODE", p_bankHeader.TRAN_CODE);
        xmlWriter.writeElementString("SERVICE_CODE", getBankConfig().getMapValueByKey("SERVICE_CODE", p_bankHeader.TRAN_CODE));
        xmlWriter.writeElementString("SEQ_NO", p_bankHeader.SEQ_NO);
        xmlWriter.writeElementString("USER_ID", getBankConfig().getMapValueByKey("Sys_Head", "USER_ID"));
        xmlWriter.writeElementString("BRANCH_ID", getBankConfig().getMapValueByKey("Sys_Head", "BRANCH_ID"));
        xmlWriter.writeElementString("SOURCE_TYPE", getBankConfig().getMapValueByKey("Sys_Head", "SOURCE_TYPE"));
        //xmlWriter.writeElementString("WS_ID", getBankConfig().getMapValueByKey("Sys_Head", "WS_ID"));
        xmlWriter.writeElementString("WS_ID", p_bankHeader.USER_IP);//客户端IP
        xmlWriter.writeElementString("CONSUMER_ID", getBankConfig().getMapValueByKey("Sys_Head", "CONSUMER_ID"));
        xmlWriter.writeElementString("TRAN_DATE", p_bankHeader.TRAN_DATE);
        xmlWriter.writeElementString("TRAN_TIMESTAMP", p_bankHeader.TRAN_TIMESTAMP);
        //xmlWriter.writeElementString("SERVER_ID", getBankConfig().getMapValueByKey("Sys_Head", "SERVER_ID"));
        xmlWriter.writeElementString("SERVER_ID", p_bankHeader.SERVER_IP);//应用服务器IP地址
        xmlWriter.writeElementString("SOURCE_BRANCH_NO", "");
        xmlWriter.writeElementString("DEST_BRANCH_NO", "");
        xmlWriter.writeElementString("TRAN_MODE", "ONLINE");
        xmlWriter.writeEndElement();

        xmlWriter.writeStartElement("Body");
        XElement tmpElement = new XElement("APP_HEAD", "");
        tmpElement.addChild(new XElement("PGUP_OR_PGDN", getBankConfig().getMapValueByKey("APP_HEAD", "PGUP_OR_PGDN")));
        tmpElement.addChild(new XElement("TOTAL_NUM", getBankConfig().getMapValueByKey("APP_HEAD", "TOTAL_NUM")));
        tmpElement.addChild(new XElement("CURRENT_NUM", getBankConfig().getMapValueByKey("APP_HEAD", "CURRENT_NUM")));
        tmpElement.addChild(new XElement("TOTAL_FLAG", getBankConfig().getMapValueByKey("APP_HEAD", "TOTAL_FLAG")));
        tmpElement.addChild(new XElement("AUTH_FLAG", getBankConfig().getMapValueByKey("APP_HEAD", "AUTH_FLAG")));
        tmpElement.addChild(new XElement("MODULE_ID", getBankConfig().getMapValueByKey("APP_HEAD", "MODULE_ID")));
        tmpElement.addChild(new XElement("USER_LANG", getBankConfig().getMapValueByKey("APP_HEAD", "USER_LANG")));
        tmpElement.addChild(new XElement("PAGE_START", getBankConfig().getMapValueByKey("APP_HEAD", "PAGE_START")));
        tmpElement.addChild(new XElement("PAGE_END", getBankConfig().getMapValueByKey("APP_HEAD", "PAGE_END")));
        tmpElement.addChild(new XElement("PROGRAM_ID", ""));
        //tmpElement.addChild(new XElement("TRAN_TYPE", getBankConfig().getMapValueByKey("APP_HEAD", "TRAN_TYPE")));
        String tran_type = getBankConfig().getMapValueByKey("TRAN_TYPE", p_bankHeader.TRAN_CODE);
        if(StringHelper.isNullOrEmpty(tran_type)) {
            //默认值MB01是测试过的，现在的默认值为WY01，如果WY01不行改回MB01
            tran_type = getBankConfig().getMapValueByKey("TRAN_TYPE", "DEFAULTTYPE");
        }
        tmpElement.addChild(new XElement("TRAN_TYPE", tran_type));
        tmpElement.addChild(new XElement("FILE_PATH", ""));
        xmlWriter.writeXElement(tmpElement);
    }

    protected void writeCommonHeaderExchangeRate(XmlTextWriter xmlWriter, ZYB02Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.TRAN_CODE)) {
            throw new Exception("未赋值trsCode");
        }

        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Sys_Head");

        xmlWriter.writeElementString("TRAN_CODE", p_bankHeader.TRAN_CODE);
        xmlWriter.writeElementString("SERVICE_CODE", "SVR_INQUIRY");
        xmlWriter.writeElementString("SEQ_NO", p_bankHeader.SEQ_NO);
        xmlWriter.writeElementString("USER_ID", getBankConfig().getMapValueByKey("Sys_Head", "USER_ID"));
        xmlWriter.writeElementString("BRANCH_ID", getBankConfig().getMapValueByKey("Sys_Head", "BRANCH_ID"));
        xmlWriter.writeElementString("SOURCE_TYPE", "CB");
        //xmlWriter.writeElementString("WS_ID", getBankConfig().getMapValueByKey("Sys_Head", "WS_ID"));
        xmlWriter.writeElementString("WS_ID", p_bankHeader.USER_IP);//客户端IP
        xmlWriter.writeElementString("CONSUMER_ID", getBankConfig().getMapValueByKey("Sys_Head", "USER_ID"));
        xmlWriter.writeElementString("TRAN_DATE", p_bankHeader.TRAN_DATE);
        xmlWriter.writeElementString("TRAN_TIMESTAMP", p_bankHeader.TRAN_TIMESTAMP);
        xmlWriter.writeElementString("CONSUMER_ID", getBankConfig().getMapValueByKey("Sys_Head", "CONSUMER_ID"));
        //xmlWriter.writeElementString("SERVER_ID", getBankConfig().getMapValueByKey("Sys_Head", "SERVER_ID"));
        xmlWriter.writeElementString("SERVER_ID", p_bankHeader.SERVER_IP);//应用服务器IP地址
        xmlWriter.writeElementString("SOURCE_BRANCH_NO", "");
        xmlWriter.writeElementString("DEST_BRANCH_NO", "");
        xmlWriter.writeElementString("TRAN_MODE", "ONLINE");
        xmlWriter.writeEndElement();

        xmlWriter.writeStartElement("Body");
        XElement tmpElement = new XElement("APP_HEAD", "");
        tmpElement.addChild(new XElement("PGUP_OR_PGDN", getBankConfig().getMapValueByKey("APP_HEAD", "PGUP_OR_PGDN")));
        tmpElement.addChild(new XElement("TOTAL_NUM", getBankConfig().getMapValueByKey("APP_HEAD", "TOTAL_NUM")));
        tmpElement.addChild(new XElement("CURRENT_NUM", getBankConfig().getMapValueByKey("APP_HEAD", "CURRENT_NUM")));
        tmpElement.addChild(new XElement("TOTAL_FLAG", getBankConfig().getMapValueByKey("APP_HEAD", "TOTAL_FLAG")));
        tmpElement.addChild(new XElement("AUTH_FLAG", getBankConfig().getMapValueByKey("APP_HEAD", "AUTH_FLAG")));
        tmpElement.addChild(new XElement("MODULE_ID", getBankConfig().getMapValueByKey("APP_HEAD", "MODULE_ID")));
        tmpElement.addChild(new XElement("USER_LANG", getBankConfig().getMapValueByKey("APP_HEAD", "USER_LANG")));
        tmpElement.addChild(new XElement("PAGE_START", getBankConfig().getMapValueByKey("APP_HEAD", "PAGE_START")));
        tmpElement.addChild(new XElement("PAGE_END", getBankConfig().getMapValueByKey("APP_HEAD", "PAGE_END")));
        tmpElement.addChild(new XElement("PROGRAM_ID", ""));
        //tmpElement.addChild(new XElement("TRAN_TYPE", getBankConfig().getMapValueByKey("APP_HEAD", "TRAN_TYPE")));
        String tran_type = getBankConfig().getMapValueByKey("TRAN_TYPE", p_bankHeader.TRAN_CODE);
        if(StringHelper.isNullOrEmpty(tran_type)) {
            //默认值MB01是测试过的，现在的默认值为WY01，如果WY01不行改回MB01
            tran_type = getBankConfig().getMapValueByKey("TRAN_TYPE", "DEFAULTTYPE");
        }
        tmpElement.addChild(new XElement("TRAN_TYPE", tran_type));
        tmpElement.addChild(new XElement("FILE_PATH", ""));
        xmlWriter.writeXElement(tmpElement);
    }

    protected void writeCommonHeaderAccrossBank(XmlTextWriter xmlWriter, ZYB02Header p_bankHeader,String serviceCode) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.TRAN_CODE)) {
            throw new Exception("未赋值trsCode");
        }

        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Sys_Head");

        xmlWriter.writeElementString("TRAN_CODE", p_bankHeader.TRAN_CODE);
        xmlWriter.writeElementString("SERVICE_CODE",serviceCode);
        xmlWriter.writeElementString("SEQ_NO", p_bankHeader.SEQ_NO);
        xmlWriter.writeElementString("USER_ID", getBankConfig().getMapValueByKey("Sys_Head", "USER_ID"));
        xmlWriter.writeElementString("CUSTOMER_ID", "");
        xmlWriter.writeElementString("BRANCH_ID", getBankConfig().getMapValueByKey("Sys_Head", "BRANCH_ID"));
        xmlWriter.writeElementString("SOURCE_TYPE", getBankConfig().getMapValueByKey("Sys_Head", "SOURCE_TYPE"));
        //xmlWriter.writeElementString("WS_ID", getBankConfig().getMapValueByKey("Sys_Head", "WS_ID"));
        xmlWriter.writeElementString("WS_ID", p_bankHeader.USER_IP);//客户端IP
        xmlWriter.writeElementString("CONSUMER_ID", getBankConfig().getMapValueByKey("Sys_Head", "CONSUMER_ID"));
        xmlWriter.writeElementString("TRAN_DATE", p_bankHeader.TRAN_DATE.replace("-",""));
        xmlWriter.writeElementString("TRAN_TIMESTAMP", p_bankHeader.TRAN_TIMESTAMP.replace(":","")
        .replace(".",""));
        //xmlWriter.writeElementString("SERVER_ID", getBankConfig().getMapValueByKey("Sys_Head", "SERVER_ID"));
        xmlWriter.writeElementString("SERVER_ID", p_bankHeader.SERVER_IP);//应用服务器IP地址
        xmlWriter.writeElementString("SOURCE_BRANCH_NO", "");
        xmlWriter.writeElementString("DEST_BRANCH_NO", "");
        xmlWriter.writeElementString("TRAN_MODE", "ONLINE");
        xmlWriter.writeEndElement();

        xmlWriter.writeStartElement("Body");
        XElement tmpElement = new XElement("APP_HEAD", "");
        tmpElement.addChild(new XElement("PGUP_OR_PGDN", getBankConfig().getMapValueByKey("APP_HEAD", "PGUP_OR_PGDN")));
        tmpElement.addChild(new XElement("TOTAL_NUM", getBankConfig().getMapValueByKey("APP_HEAD", "TOTAL_NUM")));
        tmpElement.addChild(new XElement("CURRENT_NUM", getBankConfig().getMapValueByKey("APP_HEAD", "CURRENT_NUM")));
        tmpElement.addChild(new XElement("TOTAL_FLAG", getBankConfig().getMapValueByKey("APP_HEAD", "TOTAL_FLAG")));
        tmpElement.addChild(new XElement("AUTH_FLAG", getBankConfig().getMapValueByKey("APP_HEAD", "AUTH_FLAG")));
        tmpElement.addChild(new XElement("MODULE_ID", getBankConfig().getMapValueByKey("APP_HEAD", "MODULE_ID")));
        tmpElement.addChild(new XElement("USER_LANG", getBankConfig().getMapValueByKey("APP_HEAD", "USER_LANG")));
        tmpElement.addChild(new XElement("PAGE_START", getBankConfig().getMapValueByKey("APP_HEAD", "PAGE_START")));
        tmpElement.addChild(new XElement("PAGE_END", getBankConfig().getMapValueByKey("APP_HEAD", "PAGE_END")));
        tmpElement.addChild(new XElement("PROGRAM_ID", ""));
        //tmpElement.addChild(new XElement("TRAN_TYPE", getBankConfig().getMapValueByKey("APP_HEAD", "TRAN_TYPE")));
        String tran_type = getBankConfig().getMapValueByKey("TRAN_TYPE", p_bankHeader.TRAN_CODE);
        if(StringHelper.isNullOrEmpty(tran_type)) {
            //默认值MB01是测试过的，现在的默认值为WY01，如果WY01不行改回MB01
            tran_type = getBankConfig().getMapValueByKey("TRAN_TYPE", "DEFAULTTYPE");
        }
        tmpElement.addChild(new XElement("TRAN_TYPE", tran_type));
        tmpElement.addChild(new XElement("FILE_PATH", ""));
        xmlWriter.writeXElement(tmpElement);
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        int length = p_reqStr.getBytes(Charset.forName(getCharset())).length;
        String lengthString = StringHelper.padLeft(StringHelper.valueOf(length), 6, '0');
        p_reqStr = lengthString + p_reqStr;

        String[] retStr = new String[]{"", ""};

        String serverIP = getBankConfig().getMapValueByKey("ACROSSBANK","serverIP");
        String serverPort = getBankConfig().getMapValueByKey("ACROSSBANK","DPserverPort");

        WriteBankLogLn("1.提交银行的地址：" + serverIP + ":" + serverPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(serverIP, Integer.parseInt(serverPort), this);

        String tmpCharset = getCharset();
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);

        WriteBankLogStep2(p_reqStr);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            String returnMessage = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
            WriteBankLogStep3(returnMessage);
            String returnLength = returnMessage.substring(0, 6);
            returnMessage = returnMessage.substring(6, returnMessage.length());
            String megLength = StringHelper.padLeft(StringHelper.valueOf(returnMessage.getBytes(Charset.forName(getCharset())).length), 6, '0');
            if (!returnLength.equals(megLength)) {
                retStr[1] = "银行返回报文长度错误！";
            } else {
                retStr[1] = returnMessage;
            }
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        return retStr;
    }

    protected String[] sendToBankForExchangeRate(String p_reqStr) throws Exception {
        int length = p_reqStr.getBytes(Charset.forName(getCharset())).length;
        String lengthString = StringHelper.padLeft(StringHelper.valueOf(length), 6, '0');
        p_reqStr = lengthString + p_reqStr;

        String[] retStr = new String[]{"", ""};

        String serverIP = getBankConfig().getMapValueByKey("ACROSSBANK","queryExchangeRateIp");
        String serverPort = getBankConfig().getMapValueByKey("ACROSSBANK","queryExchangeRatePort");

        WriteBankLogLn("1.提交银行的地址：" + serverIP + ":" + serverPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(serverIP, Integer.parseInt(serverPort), this);

        String tmpCharset = getCharset();
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);

        WriteBankLogStep2(p_reqStr);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            String returnMessage = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
            WriteBankLogStep3(returnMessage);
            String returnLength = returnMessage.substring(0, 6);
            returnMessage = returnMessage.substring(6, returnMessage.length());
            String megLength = StringHelper.padLeft(StringHelper.valueOf(returnMessage.getBytes(Charset.forName(getCharset())).length), 6, '0');
            if (!returnLength.equals(megLength)) {
                retStr[1] = "银行返回报文长度错误！";
            } else {
                retStr[1] = returnMessage;
            }
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        return retStr;
    }

    protected String[] sendXmlToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        String serverIP = getBankConfig().getMapValueByKey("ACROSSBANK","serverIP");
        String serverPort = getBankConfig().getMapValueByKey("ACROSSBANK","serverPort");
        WriteBankLogLn("1.提交银行的地址：" + serverIP + ":" + serverPort);
        p_reqStr = p_reqStr + "\n";
        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(serverIP, Integer.parseInt(serverPort), this);
        String tmpCharset = getCharset();
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);

        WriteBankLogStep2(p_reqStr);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            String returnMessage = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
            retStr[1] = returnMessage;
            WriteBankLogStep3(retStr[1]);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        return retStr;
    }


    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</Reply_Msg>") || tmpRecNow.contains("</Message>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }

    /**
     * 根据ats流水号从文件数据库中获取银行流水号
     *
     * @param atsSerialNumber
     * @return
     */
    /*protected String getBankSerialNumberFromDB(String atsSerialNumber, StringBuilder p_sb) throws Exception {
        if (FGBiz.dspCenter.dspSet.dbConnectionSet != null) {
            try {
                Connection dbConn = null;
                try {
                    dbConn = getDbConnection();
                    Map<String, Object> reqSeqIDMap = JDBCHelper.execQuerySingle(dbConn, "select BANKREQSEQID from REQSEQIDMAPPING where REQSEQID=?", new Object[]{atsSerialNumber});
                    if (reqSeqIDMap != null && reqSeqIDMap.size() > 0) {
                        return String.valueOf(reqSeqIDMap.get("BANKREQSEQID"));
                    }
                    p_sb.append("查询为空");
                } catch (Exception ex) {
                    p_sb.append(LogHelper.getStackTrace(ex));
                    ex.printStackTrace();
                } finally {
                    if (dbConn != null) {
                        dbConn.close();
                    }
                }
            } catch (Exception ex) {
                p_sb.append(LogHelper.getStackTrace(ex));
                ex.printStackTrace();
            }
        } else {
            p_sb.append("数据库连接未配置或有误");
        }
        return p_sb.toString();
    }*/

    /**
     * 生成符合银行要求的流水号，并把生成的流水号和sts的流水号映射关系保存到文件数据库
     *
     * @param atsSerialNumber
     * @param transType
     * @return
     */
    /*protected String createBankSerialNumber(String bankCode, String transType, String atsSerialNumber) throws Exception {
        //银行流水号编码规则：系统编号(MBC)+交易日期(yyyyMMdd)+柜员号(000000)+顺序号(0001-5000)+交易序号(0)
        StringBuilder errMsg = new StringBuilder();
        String bankSerialNumber = "";
        synchronized (this) {
            //先查询当天已经生成的最大顺序号
            int currentMaxOrderNumber = countReqSeqIDMapping(bankCode, new Date(), errMsg);
            if (errMsg.length() > 0) {
                throw new Exception(errMsg.toString());
            }
            String newOrderNumber = StringHelper.padLeft(StringHelper.valueOf(currentMaxOrderNumber), 4, '0');
            bankSerialNumber = getBankConfig().getValueAsString("systemCode") + Format.Date8Format.format(new Date()) +
                    getBankConfig().getValueAsString("tellerNumber") + newOrderNumber + getBankConfig().getValueAsString("tranNumber");
            boolean saved = true;//saveReqSeqIDMapping(bankCode, transType, new Date(), atsSerialNumber, bankSerialNumber, errMsg);
            if (!saved) {
                throw new Exception(errMsg.toString());
            }
        }
        return bankSerialNumber;
    }*/

    protected boolean saveReqSeqIDMapping(String p_bankCode, String p_transType, Date p_transDate, String p_atsSeqID,String p_toBankReqBatchNo, String p_toBankSeqID, StringBuilder p_sb) {
        if (FGBiz.dspCenter.dspSet.dbConnectionSet != null) {
            try {
                Connection dbConn = null;
                try {
                    dbConn = getDbConnection();
                    JDBCHelper.update(dbConn, "insert into REQSEQIDMAPPING(URID,TRANSDATE,REQSEQID,BANKREQBATCHNO,BANKREQSEQID,BANKCODE)values(?,?,?,?,?,?)", new Object[]{p_atsSeqID, Format.Date10Format.format(p_transDate), p_atsSeqID, p_toBankReqBatchNo,p_toBankSeqID, p_bankCode});
                    return true;
                } catch (Exception ex) {
                    p_sb.append(LogHelper.getStackTrace(ex));
                    ex.printStackTrace();
                } finally {
                    if (dbConn != null) {
                        dbConn.close();
                    }
                }
            } catch (Exception ex) {
                p_sb.append(LogHelper.getStackTrace(ex));
                ex.printStackTrace();
            }
        } else {
            p_sb.append("数据库连接未配置或有误");
        }
        return false;
    }

    /*private int countReqSeqIDMapping(String p_bankCode, Date p_transDate, StringBuilder p_sb) {
        if (FGBiz.dspCenter.dspSet.dbConnectionSet != null) {
            try {
                Connection dbConn = null;
                try {
                    dbConn = getDbConnection();
                    Map<String, Object> reqSeqIDMap = JDBCHelper.execQuerySingle(dbConn, "select count(*) from REQSEQIDMAPPING where TRANSDATE=? and BANKCODE=?", new Object[]{Format.Date10Format.format(p_transDate), p_bankCode});
                    if (reqSeqIDMap != null && reqSeqIDMap.size() > 0) {
                        return Integer.parseInt(String.valueOf(reqSeqIDMap.get("count(*)")));
                    }
                    p_sb.append("查询为空");
                } catch (Exception ex) {
                    p_sb.append(LogHelper.getStackTrace(ex));
                    ex.printStackTrace();
                } finally {
                    if (dbConn != null) {
                        dbConn.close();
                    }
                }
            } catch (Exception ex) {
                p_sb.append(LogHelper.getStackTrace(ex));
                ex.printStackTrace();
            }
        } else {
            p_sb.append("数据库连接未配置或有误");
        }
        return -1;
    }*/

    protected Map<String,String> getIpInfoMap(String atsReqXml) {
        Map<String,String> ipInfoMap = new HashMap<String,String>();
        ipInfoMap.put("userIP","");
        ipInfoMap.put("serverIP","");
        XmlTextReader xmlTextReader = new XmlTextReader(atsReqXml);
        String userIP = "";
        String serverIP = "";
        try {
            userIP = xmlTextReader.getSimpleText("UserIP");
            serverIP = xmlTextReader.getSimpleText("ServerIP");
        } catch (Exception e) {
            WriteBankLogLn("获取IP信息发生异常："+e.getMessage());
        }
        ipInfoMap.put("userIP",userIP);
        ipInfoMap.put("serverIP",serverIP);
        return ipInfoMap;
    }

    protected Connection getDbConnection() throws Exception {
        Connection conn=null;
        String dbDriver = getBankConfig().getMapValueByKey("DBCONFIG","dbDriver");
        String dbUrl = getBankConfig().getMapValueByKey("DBCONFIG","dbUrl");
        String dbUser = getBankConfig().getMapValueByKey("DBCONFIG","dbUser");
        String dbPassword = decodePassword(getBankConfig().getMapValueByKey("DBCONFIG","dbPassword"));
        Class.forName(dbDriver).newInstance();
        conn=DriverManager.getConnection(dbUrl, dbUser, dbPassword);
        return conn;
    }

    /**
     * 数据库密码解密
     * @param encryptPassword
     * @return
     * @throws Exception
     */
    private String decodePassword(String encryptPassword) throws Exception {
        //System.out.println(SecureIdentityUtil.encode("123456"));//208dc1882a22c525
        String isPasswordEncrypt = getBankConfig().getMapValueByKey("DBCONFIG","isPasswordEncrypt");
        if("0".equals(isPasswordEncrypt)) {
            return encryptPassword;
        } else {
            return new String(SecureIdentityUtil.decode(encryptPassword));
        }
    }
}
